package com.hornet.manager.weixin.web.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.hornet.commons.utils.SHA1;
import com.hornet.commons.web.BaseController;
import com.hornet.manager.weixin.constant.WeixinConstant;
import com.hornet.manager.weixin.util.WeixinHandler;

@Controller
@RequestMapping("/weixin")
public class WeixinController extends BaseController {

	private static final String TOKEN = WeixinConstant.TOKEN ;
	
	/**
	 * 微信接入
	 * @param request
	 * @param response
	 */
	@RequestMapping(method=RequestMethod.GET)
	public void connect(HttpServletRequest request, HttpServletResponse response) {
		try {
			logger.info("RemoteAddr: "+ request.getRemoteAddr());  
			logger.info("QueryString: "+ request.getQueryString());  
	        
			//接收微信发送过来的参数
			String signature = request.getParameter("signature");	// 微信加密签名  
			String timestamp = request.getParameter("timestamp");	// 时间戳  
			String nonce = request.getParameter("nonce");			// 随机数  
			String echostr = request.getParameter("echostr");		//随机字符串  
			
			//1. 将token、timestamp、nonce三个参数进行字典序排序  
			String[] str = { TOKEN, timestamp, nonce };  
			Arrays.sort(str); 
			
			//2. 将三个参数字符串拼接成一个字符串进行sha1加密  
			String digest = SHA1.encode(str[0] + str[1] + str[2]);  
	        
			//3. 确认请求来至微信  
			if (digest.equals(signature)) {  
				//完成相互认证
			    response.getWriter().write(echostr);  
			    logger.info("微信服务器接入生效..........");  
			} else {
				logger.info("微信服务器接入失败..........");  
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		}  
	}
	
	@RequestMapping(method=RequestMethod.POST)
	public void wexinMessageHandler(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 将请求、响应的编码均设置为UTF-8（防止中文乱码）  
        request.setCharacterEncoding("UTF-8");  
        response.setCharacterEncoding("UTF-8"); 
        // 调用核心业务类接收消息、处理消息  
        String respMessage = WeixinHandler.processRequest(request);  
          
        // 响应消息  
        PrintWriter out = response.getWriter();  
        out.print(respMessage);
        out.close(); 
	}
	
}
